import { StaticInstance } from "../StaticInstance";
import { GAME_DATA } from "../manager/DataManager";

// carolsail
const { ccclass, property } = cc._decorator;

export enum CAR_STATE {
    IDLE = 'car_idle',
    MOVE = 'car_move',
}


@ccclass
export default class Car extends cc.Component {

    colorIndex: number = 0
    isMoving: boolean = false
    moveSpeed: number = 20
    state: CAR_STATE = CAR_STATE.IDLE
    xEnd: number = 0
    playerKeyArr: number[] = []
    playerNums: number = 0

    init(colorIndex: number) {
        this.colorIndex = colorIndex
        const color = new cc.Color().fromHEX(GAME_DATA.COLORS[colorIndex])
        this.node.color = color
        this.node.children.forEach(player => {
            player.color = color
        })
        this.state = CAR_STATE.IDLE
    }

    setMove(start: number, end: number) {
        this.xEnd = end
        if (this.node.x != start) this.node.setPosition(start, 0)
        this.state = CAR_STATE.MOVE
        this.isMoving = true
        StaticInstance.gameManager.getLevelComp().onCarMoveCallBack(this.xEnd)
    }

    rendorPlayer(angle: number) {
        const players = this.node.children
        const playerNode = players[this.playerNums]
        playerNode.angle = angle
        playerNode.active = true
        this.playerNums += 1
        // for (let i = 0; i < this.playerNums; i++) {
        //     players[i].active = true
        // }
    }

    protected update(dt: number): void {
        if (this.isMoving) {
            this.node.x += this.moveSpeed
            if (this.node.x >= this.xEnd) {
                this.state = CAR_STATE.IDLE
                this.isMoving = false
                this.node.x = this.xEnd
                StaticInstance.gameManager.getLevelComp().onCarMoveEndCallBack(this)
            }
        }
    }
}
